package web.importations.action;

import com.opensymphony.xwork2.ActionSupport;
import domain.entities.*;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import services.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: vgonzalez
 * Date: 21/09/12
 * Time: 11:59
 * To change this template use File | Settings | File Templates.
 */

@Namespace("/Importations")
public class ImportationsController extends ActionSupport {

    private List<Droga> drogaList;
    private List<Compromisopais> paisList;
    private List<Protocolo> protocolList = new ArrayList<Protocolo>();

    private DrogaService drogaService;
    private CompromisoPaisService paisService;
    private ProtocolCRUDService protService;
    private ImportacionService importService;
    private DrogaImportacionService drogaImportacionService;

    private List<Importacion> list = new ArrayList<Importacion>();
    private Importacion importacion = new Importacion();
    private Protocolo protocolo;

    private Droga droga;
    private List<Protocolo> protocolSearchList = new ArrayList<Protocolo>();

    private List<String> quantities = new ArrayList<String>();

    private Integer editableImportationId;
    private Integer drogaImpToDiscountId;
    private String protocolToDiscountId;
    private Integer takeOff;

    private Integer totalDescontado;

    private DrogaImportacion drogaImportacion;

    @Autowired
    public ImportationsController(DrogaService drogaService, CompromisoPaisService paisService, ProtocolCRUDService protService, ImportacionService importService, DrogaImportacionService drogaImportacionService){
        this.protService = protService;
        this.drogaService = drogaService;
        this.paisService = paisService;
        this.importService = importService;
        this.drogaImportacionService = drogaImportacionService;
        drogaList = drogaService.getDrogas();
        paisList = paisService.findAll();
        protocolSearchList = protService.getProtocols();
        protocolList = new ArrayList<Protocolo>();
    }

    @Action(value="main", results={
            @Result(name="success", location="/importations.tiles", type="tiles")
    })
    public String execute() {
        return SUCCESS;
    }

    @Action(value="cancelDiscount", results={
            @Result(name="success", location="/importations.tiles", type="tiles")
    })
    public String cancel() {
        drogaImportacion = null;
        importacion = null;
        return SUCCESS;
    }

    @Action(value="create", results={
            @Result(name="success", location="/importations.tiles.create", type="tiles")
    })
    public String create() {
        if(editableImportationId != null){
            importacion = importService.findById(editableImportationId);
            totalDescontado = 0;
            Iterator<ProtocoloImportacion> itDisc = importacion.getProtocoloImportaciones().iterator();
            while(itDisc.hasNext()){
                totalDescontado += itDisc.next().getTakeOff();
            }
        }
        return SUCCESS;
    }

    @Action(value="discount", results={
            @Result(name="success", location="/importations.tiles.discount", type="tiles")
    })
    public String discount() {
        if(drogaImpToDiscountId != null){
            drogaImportacion = drogaImportacionService.findById(drogaImpToDiscountId);
            Iterator<ProtocoloImportacion> itProt = drogaImportacion.getImportacion().getProtocoloImportaciones().iterator();
            while(itProt.hasNext()){
                ProtocoloImportacion actual = itProt.next();
                Protocolo protocoloActual = actual.getProtocolo();
                if(protocoloActual != null && actual.getFecha() == null)
                    protocolList.add(protocoloActual);
            }
        }
        importacion = null;
        return SUCCESS;
    }

    @Action(value="detail", results={
            @Result(name="success", location="/importations.tiles.detail", type="tiles")
    })
    public String detail() {
        if(drogaImpToDiscountId != null){
            drogaImportacion = drogaImportacionService.findById(drogaImpToDiscountId);
        /*    Iterator<ProtocoloImportacion> itProt = drogaImportacion.getImportacion().getProtocoloImportaciones().iterator();
            while(itProt.hasNext()){
                ProtocoloImportacion actual = itProt.next();
                Protocolo protocoloActual = actual.getProtocolo();
                if(protocoloActual != null && actual.getFecha() == null)
                    protocolList.add(protocoloActual);
            }*/
        }
        importacion = null;
        return SUCCESS;
    }

    @Action(value="saveDiscount", results={
            @Result(name="success", location="/importations.tiles", type="tiles")
    })
    public String saveDiscount() {
        Importacion imp = importService.findById(drogaImportacion.getImportacion().getId());
        drogaImportacion.setDroga(drogaService.findById(drogaImportacion.getDroga().getId()));
        drogaImportacion.setImportacion(imp);
        drogaImportacion.setCurrentBalance(drogaImportacion.getCurrentBalance() - takeOff);

        ProtocoloImportacion protImp = new ProtocoloImportacion();
        protImp.setProtocolo(protService.findById(protocolToDiscountId));
        protImp.setImportacion(imp);
        protImp.setDrogaImportacion(drogaImportacion);
        protImp.setFecha(new Date());
        protImp.setTakeOff(takeOff);

        drogaImportacion.addProtocoloImportacion(protImp);
        drogaImportacionService.save(drogaImportacion);

        drogaImportacion = null;
        importacion = null;
        protocolList.clear();

        return SUCCESS;
    }

    @Action(value="list", results={
            @Result(name="success", location="/importations.tiles", type="tiles")
    })
    public String list() {
        CriteriaImportation cr = new CriteriaImportation(importacion);
        Compromisopais pais = paisService.findById(importacion.getCompromisopais().getId());
        cr.setPais(pais);
        droga = drogaService.findById(droga.getId());
        cr.setDroga(droga);
        protocolo = protService.findById(protocolo.getId());
        cr.setProtocolo(protocolo);
        list = importService.list(cr);

        return SUCCESS;
    }

    @Action(value="save", results={
            @Result(name="success", location="/importations.tiles", type="tiles")
    })
    public String save() {
        Compromisopais pais = paisService.findById(importacion.getCompromisopais().getId());
        importacion.setCompromisopais(pais);
        if(importacion.getId() == null || importacion.getId().equals("")){
            pais.addImportacion(importacion);
        }

        Iterator<DrogaImportacion> itDI = importacion.getDrogaImportaciones().iterator();
        int i = 0;
        List<Integer> aBorrar = new ArrayList<Integer>();
        while(itDI.hasNext()){
            DrogaImportacion actual = itDI.next();
            if(actual != null){
                Droga droga = drogaService.findById(actual.getDroga().getId());
                actual.setInitialQty(Integer.parseInt(quantities.get(i)));
                actual.setCurrentBalance(Integer.parseInt(quantities.get(i)));
                actual.setDroga(droga);
                actual.setImportacion(importacion);
                if(actual.getId() == null){
                    droga.addDrogaImportacion(actual);
                }
            }
            else{
                aBorrar.add(i);
            }
            i++;
        }

        Iterator<Integer> itIndexes = aBorrar.iterator();
        int borrados = 0;
        while(itIndexes.hasNext()){
            importacion.getDrogaImportaciones().remove(itIndexes.next() - borrados);
            borrados++;
        }

        aBorrar.clear();

        Iterator<ProtocoloImportacion> itProt = importacion.getProtocoloImportaciones().iterator();
        i = 0;
        while(itProt.hasNext()){
            ProtocoloImportacion actual = itProt.next();
            if(actual != null){
                Protocolo prot = protService.findById(actual.getProtocolo().getId());
                actual.setFecha(null);
                if(actual.getId() == null){
                    prot.addProtocoloImportacion(actual);
                }
                actual.setProtocolo(prot);
                actual.setTakeOff(0);
                actual.setImportacion(importacion);
            }
            else{
                aBorrar.add(i);
            }
        }

        itIndexes = aBorrar.iterator();
        borrados = 0;
        while(itIndexes.hasNext()){
            importacion.getProtocoloImportaciones().remove(itIndexes.next() - borrados);
            borrados++;
        }

        importService.attachDirty(importacion);

        importacion = new Importacion();
        protocolList.clear();

        return SUCCESS;
    }

    public List<Compromisopais> getPaisList() {
        return paisList;
    }

    public void setPaisList(List<Compromisopais> paisList) {
        this.paisList = paisList;
    }

    public List<Droga> getDrogaList() {
        return drogaList;
    }

    public void setDrogaList(List<Droga> drogaList) {
        this.drogaList = drogaList;
    }

    public Importacion getImportacion() {
        return importacion;
    }

    public void setImportacion(Importacion importacion) {
        this.importacion = importacion;
    }

    public Integer getTotalDescontado() {
        return totalDescontado;
    }

    public void setTotalDescontado(Integer totalDescontado) {
        this.totalDescontado = totalDescontado;
    }

    public DrogaImportacion getDrogaImportacion() {
        return drogaImportacion;
    }

    public void setDrogaImportacion(DrogaImportacion drogaImportacion) {
        this.drogaImportacion = drogaImportacion;
    }

    public Protocolo getProtocolo() {
        return protocolo;
    }

    public void setProtocolo(Protocolo protocolo) {
        this.protocolo = protocolo;
    }

    public List<Importacion> getList() {
        return list;
    }

    public void setList(List<Importacion> list) {
        this.list = list;
    }


    public List<Protocolo> getProtocolList() {
        return protocolList;
    }

    public void setProtocolList(List<Protocolo> protocolList) {
        this.protocolList = protocolList;
    }

    public List<String> getQuantities() {
        return quantities;
    }

    public void setQuantities(List<String> quantities) {
        this.quantities = quantities;
    }

    public Droga getDroga() {
        return droga;
    }

    public void setDroga(Droga droga) {
        this.droga = droga;
    }

    public List<Protocolo> getProtocolSearchList() {
        return protocolSearchList;
    }

    public void setProtocolSearchList(List<Protocolo> protocolSearchList) {
        this.protocolSearchList = protocolSearchList;
    }

    public Integer getEditableImportationId() {
        return editableImportationId;
    }

    public void setEditableImportationId(Integer editableImportationId) {
        this.editableImportationId = editableImportationId;
    }

    public Integer getTakeOff() {
        return takeOff;
    }

    public void setTakeOff(Integer takeOff) {
        this.takeOff = takeOff;
    }

    public String getProtocolToDiscountId() {
        return protocolToDiscountId;
    }

    public void setProtocolToDiscountId(String protocolToDiscountId) {
        this.protocolToDiscountId = protocolToDiscountId;
    }

    public Integer getDrogaImpToDiscountId() {
        return drogaImpToDiscountId;
    }

    public void setDrogaImpToDiscountId(Integer drogaImpToDiscountId) {
        this.drogaImpToDiscountId = drogaImpToDiscountId;
    }
}
